//------------------------------------------------------------------------------
//
//   author: 小兵（aosnow@yeah.net）
//   create: 2012-5-29 下午22:36:19
//    class: BinaryLoader - 文件字节数据加载类
//
//------------------------------------------------------------------------------

package starfire.rpc.loader.elements
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import starfire.rpc.URL;
	import starfire.rpc.loader.LoadMessage;
	import starfire.rpc.loader.LoadState;

	[ExcludeClass]
	public class BinaryLoader extends LoaderBase
	{
		protected var urlLoader:URLLoader;

		public function BinaryLoader( message:LoadMessage, decryption:Function = null )
		{
			super( message );
		}

		override public function canHandleResource():Boolean
		{
			if( super.message )
			{
				var url:URL = new URL( super.message.url );
				return ( url.path.search( /\.\w+$/i ) != -1 );
			}

			return false;
		}

		override protected function executeLoad( message:LoadMessage ):void
		{
			var urlReq:URLRequest = new URLRequest( message.url );

			/**
			 * 因为有可能被加载的SWF不再是完整的或者已经过加密处理，所以只能通过二进制下载，
			 * 再经过相应的字节解密，才能通过loader.loadBytes来获取
			 */
			urlLoader = new URLLoader();
			urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
			toggleLoaderListeners( urlLoader, true );

			// 开始加载数据
			try
			{
				updateLoadState( LoadState.LOADING );
				urlLoader.load( urlReq );
			}
			catch( ioError:IOError )
			{
				IOErrorHandler( null, ioError.message );
			}
			catch( securityError:SecurityError )
			{
				securityErrorHandler( null, securityError.message );
			}
		}

		override protected function executeUnload( message:LoadMessage ):void
		{
			updateLoadState( LoadState.UNLOADING );
			urlLoader = null;
			updateLoadState( LoadState.UNINITIALIZED );
		}

		override protected function loadCompleteHandler( event:Event ):void
		{
			toggleLoaderListeners( urlLoader, false );

			var data:ByteArray = urlLoader.data as ByteArray;

			// 文件数据保存字节数组
			try
			{
				saveCache( data );
			}
			catch( e:Error )
			{
				return;
			}

			updateLoadState( LoadState.READY );

			// 执行回调函数
			if( complete is Function )
			{
				complete( data );
			}
		}
	}
}
